package com.gateway.register.client.nacos;

import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.gateway.common.constant.Constants;
import com.gateway.common.constant.NacosPathConstants;
import com.gateway.common.exception.GatewayException;
import com.gateway.common.utils.ContextPathUtils;
import com.gateway.common.utils.JsonUtils;
import com.gateway.register.client.api.GatewayClientRegisterRepository;
import com.gateway.register.common.config.GatewayRegisterCenterConfig;
import com.gateway.register.common.dto.MetaDataRegisterDTO;
import com.gateway.register.common.dto.RouteRegisterDTO;
import com.gateway.register.common.path.RegisterPathConstants;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/1/29 22:59
 **/
public class NacosClientRegisterRepository implements GatewayClientRegisterRepository  {
    private static final Logger log = LoggerFactory.getLogger(NacosClientRegisterRepository.class);

    private static final String NAMESPACE = "nacosNamespace";

    private static final String ROUTE_META_DATA = "routeMetadata";

    private ConfigService configService;

    private NamingService namingService;

    private final ConcurrentLinkedQueue<String> metadataCache = new ConcurrentLinkedQueue<>();
//
//    public NacosClientRegisterRepository(final GatewayRegisterCenterConfig config) {
//        init(config);
//    }

    @Override
    public void init(GatewayRegisterCenterConfig config) {
        String serverAddr = config.getServerLists();
        Properties properties = config.getProps();
        Properties nacosProperties = new Properties();
        nacosProperties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        nacosProperties.put(PropertyKeyConst.NAMESPACE, properties.getProperty(NAMESPACE));
        nacosProperties.put(PropertyKeyConst.USERNAME, properties.getProperty(PropertyKeyConst.USERNAME, ""));
        nacosProperties.put(PropertyKeyConst.PASSWORD, properties.getProperty(PropertyKeyConst.PASSWORD, ""));
        nacosProperties.put(PropertyKeyConst.ACCESS_KEY, properties.getProperty(PropertyKeyConst.ACCESS_KEY, ""));
        nacosProperties.put(PropertyKeyConst.SECRET_KEY, properties.getProperty(PropertyKeyConst.SECRET_KEY, ""));

        try {
            this.configService = ConfigFactory.createConfigService(nacosProperties);
            this.namingService = NamingFactory.createNamingService(nacosProperties);
        } catch (NacosException e) {
            throw new GatewayException(e);
        }
    }

    @Override
    public void persistInterface(MetaDataRegisterDTO metaDataDTO) {
        String rpcType = metaDataDTO.getRpcType();
        String contextPath = ContextPathUtils.buildRealNode(metaDataDTO.getContextPath(), metaDataDTO.getAppName());
        registerConfig(rpcType, contextPath, metaDataDTO);
    }

    @Override
    public void persistRoute(RouteRegisterDTO routeRegisterDTO) {
        String rpcType = routeRegisterDTO.getRpcType();
        String contextPath = ContextPathUtils.buildRealNode(routeRegisterDTO.getContextPath(), routeRegisterDTO.getAppName());
        String host = routeRegisterDTO.getHost();
        Integer port = routeRegisterDTO.getPort();
        registerService(rpcType, contextPath, host, port, routeRegisterDTO);
    }

    @Override
    public void close() {
        try {
            configService.shutDown();
            namingService.shutDown();
        } catch (NacosException e) {
            log.error("NacosClientRegisterRepository close error!", e);
        }
    }

    private synchronized void registerConfig(final String rpcType,
                                             final String contextPath,
                                             final MetaDataRegisterDTO metadata) {
        metadataCache.add(JsonUtils.toJsonString(metadata));
        String configName = RegisterPathConstants.buildServiceConfigPath(rpcType, contextPath);
        try {
            final String defaultGroup = NacosPathConstants.GROUP;
            if (configService.publishConfig(configName,
                    defaultGroup,
                    JsonUtils.toJsonString(metadataCache),
                    ConfigType.JSON.getType())) {
                log.info("register metadata success: {}", metadata.getQualifiedName());
            } else {
                throw new GatewayException("register metadata fail , please check ");
            }
        } catch (NacosException e) {
            throw new GatewayException(e);
        }
    }

    private synchronized void registerService(final String rpcType,
                                              final String contextPath,
                                              final String host,
                                              final int port,
                                              final RouteRegisterDTO registerDTO) {
        Instance instance = new Instance();
        instance.setEphemeral(true);
        instance.setIp(host);
        instance.setPort(port);
        Map<String, String> metadataMap = Maps.newHashMap();
        metadataMap.put(Constants.CONTEXT_PATH, contextPath);
        metadataMap.put(ROUTE_META_DATA, JsonUtils.toJsonString(registerDTO));
        instance.setMetadata(metadataMap);
        String serviceName = RegisterPathConstants.buildServiceInstancePath(rpcType);
        try {
            namingService.registerInstance(serviceName, instance);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
        log.info("register service route success : {}", serviceName);
    }
}
